<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Peizhi, Exphone};
use think\Db;
use think\facade\Log;
use app\facade\Redis;


class Eclist extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('Eclist')->setDescription('Ec所有数据导出');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        //优惠券过期检测
        $list = (new Peizhi())->where('iseclist', 1)->group('type')->order("type desc")->select();
        //更新各品牌cmrid
        Log::write('----ec列表获取star-----', 'eclist');
        foreach ($list as $peizhi) {
            $results = $this->getlist($peizhi, [0], 1);
            $this->getjsons($peizhi, $results);
            //获取sort
            $sort = $results['data']['sort'] ?? [];
            //获取总页
            $maxPageNo =  (int)$results['data']['page']['maxPageNo'] ?? 0;
            $i = 2;
            while ($i <= $maxPageNo) {
                $resultss = $this->getlist($peizhi, $sort, $i) ?? [];
                $sort = $resultss['data']['sort'] ?? [];
                $this->getjsons($peizhi, $resultss);
                $i++;
            }
        }
        Log::write('----ec列表获取end-----', 'eclist');
    }


    public function getjsons($peizhi, $results = [])
    {
        if (!empty($results['code']) && $results['code'] == 200 && !empty($results['data'])) {
            if (!empty($results['data']['list']) && count($results['data']['list']) > 0) {
                foreach ($results['data']['list'] as $rows) {
                    if (empty($rows['mobiles'][0])) {
                        continue;
                    }
                    if (!preg_match("/^1[0-9]{10}$/", $rows['mobiles'][0])) {
                        continue;
                    }
                    $str = $rows['prefecture'] ?? '';
                    $str = str_replace('中国/', '', $str);
                    $str = str_replace("/", " ", $str);
                    $addstr = explode(' ', $str);
                    $addstr[0] =  mb_substr($addstr[0] ?? '', 0, 2) ?? '';
                    $addstr[1] =  mb_substr($addstr[1] ?? '', 0, 2) ?? '';
                    $addstr = implode(' ', $addstr) ?? '';
                    $save[] = [
                        'type' => $peizhi['type'],
                        'typem' => $peizhi['type'],
                        'phone' =>  $rows['mobiles'][0] ?? "",
                        'address' => $addstr,
                        'createTime' => $rows['createTime'] ?? "",
                        'channel' => $rows['channel'] ?? "",
                        'crmId' => $rows['crmId'] ?? "",
                        'ysdata' => serialize($rows)
                    ];
                }
                if (count($save) > 0) {
                    Db::startTrans();
                    try {
                        (new Exphone())->allowfield(true)->saveAll($save);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        dump($e->getMessage());
                        Log::write($e->getMessage(), 'eclist');
                    }
                }
            }
        }
    }

    public function  getlist($peizhi, $sort, $page)
    {
        //批量查询
        $ccdata = [
            "pageSize" => 1000,
            "pageNo" => $page,
            // "createTime" => [
            //     "endTime" => $stardatetime,
            //     "startTime" => $enddatetime
            // ],
            "orderBy" => [
                [
                    "sortField" => "crmId",
                    "sortType" => "asc"
                ]
            ],
            "sort" => $sort,
        ];
        $ccjsonData = json_encode($ccdata);
        // 2. 请求服务器处理
        $ccurl = "https://open.workec.com/v2/customer/queryCustomer";
        list($ccreturnCode, $ccreturnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $ccurl, $ccjsonData);
        $ccrjson = json_decode($ccreturnContent, true) ?? [];
        Log::write($ccrjson, 'eclist');
        return $ccrjson;
    }
}
